package com.cf.redis.controller;

import com.cf.redis.common.utils.RedisUtil;
import com.cf.redis.entity.UserEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Author: YangF
 * @Date: 2021-01-22 9:38
 * @description:
 */

@Slf4j
@RequestMapping("/redis")
@RestController
public class RedisController {
    private  static int ExpireTime = 60; // redis中存储的过期时间60s

    @Resource
    private RedisUtil redisUtil;

    @RequestMapping("set")
    public boolean redisset(String key,String value){
        UserEntity userEntity = new UserEntity();
        userEntity.setId(Long.valueOf(1));
        userEntity.setGuid(String.valueOf(1));
        userEntity.setName("zhangsan");
        userEntity.setAge(String.valueOf(20));
        userEntity.setCreateTime(new Date());

//        return redisUtil.set(key,userEntity,ExpireTime);
        return redisUtil.set(key,value);
    }

    @RequestMapping("get")
    public Object redisget(String key){
        return redisUtil.get(key);
    }

    @RequestMapping("expire")
    public boolean expire(String key){
        return redisUtil.expire(key,ExpireTime);
    }



    @RequestMapping(value = "/hello/{id}")
    public String hello(@PathVariable(value = "id") String id){
        //查询缓存中是否存在
//        boolean hasKey = redisUtil.exists(id);
        boolean hasKey = redisUtil.hashKey(id);
        String str = "";
        if(hasKey){
            //获取缓存
            Object object =  redisUtil.get(id);
            log.info("从缓存获取的数据"+ object);
            str = object.toString();
        }else{
            //从数据库中获取信息
            log.info("从数据库中获取数据");
//            str = testService.test();
            //数据插入缓存（set中的参数含义：key值，user对象，缓存存在时间10（long类型），时间单位）
//            redisUtil.set(id,str,10L,TimeUnit.MINUTES);
            redisUtil.set(id,str,ExpireTime);
            log.info("数据插入缓存" + str);
        }
        return str;
    }
}
